﻿using Manon.Admin.Web.Application.Dtos;
using Manon.Admin.Web.Application.Dtos.Member;
using Manon.Admin.Web.Domain.Entities;
using Manon.Admin.Web.Domain.Repositories;
using Manon.Core;
using Manon.Core.Commons;
using Manon.Core.Extensions;
using Manon.Repository;
using Manon.Repository.Collections;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Manon.Admin.Web.Application.Impl
{
    public class MemberService : IMemberService
    {
        private readonly ILogger<MemberService> _logger;
        private readonly IMemberLevelRepository _memberLevelRepository;
        private readonly IMemberRepository _memberRepository;
        private readonly IApplicationUser _applicationUser;
        private readonly IUnitOfWork _unitOfWork;
        public MemberService(ILogger<MemberService> logger,
            IMemberLevelRepository memberLevelRepository,
            IMemberRepository memberRepository,
            IApplicationUser applicationUser,
            IUnitOfWork unitOfWork
            )
        {
            _logger = logger;
            _memberLevelRepository = memberLevelRepository;
            _memberRepository = memberRepository;
            _applicationUser = applicationUser;
            _unitOfWork = unitOfWork;
        }

        #region 会员等级
        /// <summary>
        /// 获取会员等级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<GetMemberLevelOutput> GetMemberLevel(int id)
        {
            if (id <= 0) return new GetMemberLevelOutput() { Enabled = true };

            try
            {
                var result = await _memberLevelRepository.GetFirstOrDefaultAsync(x => x.Id == id);

                return result.ConvertTo<MemberLevel, GetMemberLevelOutput>();
            }
            catch (Exception ex)
            {
                _logger.LogError("获取会员等级异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取会员等级列表
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<PagedList<GetMemberLevelOutput>> GetMemberLevelPagedList(GetMemberLevelPagedListInput Input)
        {
            try
            {
                Expression<Func<MemberLevel, bool>> predicate = x => x.IsDeleted == false;
                var result = await _memberLevelRepository.GetPagedListAsync<GetMemberLevelOutput>(predicate, Input);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError("获取资讯列表异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存会员等级 
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveMemberLevel(SaveMemberLevelInput Input)
        {
            try
            {
                var result = await _memberLevelRepository.GetFirstOrDefaultAsync(x => x.Id == Input.Id);
                if (result == null)
                {
                    result = new MemberLevel();
                    result.LevelName = Input.LevelName;
                    result.OrderIndex = Input.OrderIndex;
                    result.Enabled = Input.Enabled;
                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.OrderIndex = Input.OrderIndex;
                    result.CreateBy = _applicationUser.UserId;
                    result.UpdateBy = _applicationUser.UserId;
                    await _memberLevelRepository.InsertAsync(result);
                }
                else
                {
                    result.LevelName = Input.LevelName;
                    result.OrderIndex = Input.OrderIndex;
                    result.Enabled = Input.Enabled;
                    result.UpdateTime = DateTime.Now;
                    result.OrderIndex = Input.OrderIndex;
                    result.UpdateBy = _applicationUser.UserId;
                    await _memberLevelRepository.UpdateAsync(result);
                }
                await _unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                _logger.LogError("保存会员等级异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 设置会员等级是否可用
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SetMemberLevelEnabled(int id, bool enabled)
        {
            try
            {

                var news = await _memberLevelRepository.GetFirstOrDefaultAsync(x => x.Id == id);
                if (news == null) return null;
                news.Enabled = enabled;
                await _memberLevelRepository.UpdateAsync(news);
                await _unitOfWork.SaveChangesAsync();
                return Result.Successed("设置成功!");

            }
            catch (Exception ex)
            {
                _logger.LogError("设置会员等级是否可用异常", ex);
                throw;
            }
        }
        #endregion



        #region 会员管理

        /// <summary>
        /// 获取会员等级列表
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<List<GetMemberLevelOutput>> GetMemberLevelList()
        {
            try
            {
                var result = await _memberLevelRepository.GetQuery().OrderBy(n => n.OrderIndex).ToListAsync();
                if (result == null || result.Count == 0) return new List<GetMemberLevelOutput>();

                return result.ConvertTo<MemberLevel, GetMemberLevelOutput>();

            }
            catch (Exception ex)
            {
                _logger.LogError("获取会员等级列表异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取会员管理
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<GetMemberOutput> GetMember(int id)
        {
            if (id <= 0) return new GetMemberOutput() { Enabled = true, Sex = 1 };

            try
            {
                var result = await _memberRepository.GetFirstOrDefaultAsync(x => x.Id == id);

                return result.ConvertTo<Member, GetMemberOutput>();
            }
            catch (Exception ex)
            {
                _logger.LogError("获取会员管理异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取会员管理列表
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<PagedList<GetMemberOutput>> GetMemberPagedList(GetMemberPagedListInput Input)
        {
            try
            {
                var levels = await _memberLevelRepository.GetListAsync();

                var result = await _memberRepository
                    .GetQuery()
                    .WhereIf(Input.Enabled.HasValue, n => n.Enabled == Input.Enabled.Value)
                    .WhereIf(!string.IsNullOrEmpty(Input.Keyword), n => n.MemberName.Contains(Input.Keyword) || n.MemberCnName.Contains(Input.Keyword))
                    .WhereIf(Input.Sex > 0, n => n.Sex == Input.Sex)
                    .WhereIf(Input.Level > 0, n => n.Level == Input.Level)
                    .WhereIf(!string.IsNullOrEmpty(Input.RegisteStartTime), n => n.RegisteTime >= DateTime.Parse(Input.RegisteStartTime))
                    .WhereIf(!string.IsNullOrEmpty(Input.RegisteEndTime), n => n.RegisteTime <= DateTime.Parse(Input.RegisteEndTime))
                    .ToPagedListAsync<GetMemberOutput, Member>(Input);

                if (result != null && result.Items != null)
                {
                    foreach (var item in result.Items)
                    {
                        item.LevelName = levels?.Where(n => n.Id == item.Level).FirstOrDefault()?.LevelName;
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError("获取会员管理列表异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存会员管理
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveMember(SaveMemberInput Input)
        {
            try
            {
                var result = await _memberRepository.GetFirstOrDefaultAsync(x => x.Id == Input.Id);
                if (result == null)
                {
                    result = new Member();
                    result.Address = Input.Address ?? "";
                    result.Email = Input.Email ?? "";
                    result.HeadPortrait = Input.HeadPortrait ?? "";
                    result.Level = Input.Level;
                    result.MemberCnName = Input.MemberCnName ?? "";
                    result.MemberName = Input.MemberName ?? "";
                    result.Mobile = Input.Mobile ?? "";
                    result.Password = "";
                    result.RegisteTime = DateTime.Now;
                    result.Sex = Input.Sex;
                    result.Enabled = Input.Enabled;
                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.CreateBy = _applicationUser.UserId;
                    result.UpdateBy = _applicationUser.UserId;
                    await _memberRepository.InsertAsync(result);
                }
                else
                {
                    result.Address = Input.Address ?? "";
                    result.Email = Input.Email ?? "";
                    result.HeadPortrait = Input.HeadPortrait ?? "";
                    result.Level = Input.Level;
                    result.MemberCnName = Input.MemberCnName ?? "";
                    result.MemberName = Input.MemberName ?? "";
                    result.Mobile = Input.Mobile ?? "";
                    result.Password = "";
                    result.RegisteTime = DateTime.Now;
                    result.Sex = Input.Sex;
                    result.Enabled = Input.Enabled;
                    result.UpdateTime = DateTime.Now;
                    result.UpdateBy = _applicationUser.UserId;
                    await _memberRepository.UpdateAsync(result);
                }
                await _unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                _logger.LogError("保存会员管理异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 设置会员管理是否可用
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SetMemberEnabled(int id, bool enabled)
        {
            try
            {
                var news = await _memberRepository.GetFirstOrDefaultAsync(x => x.Id == id);
                if (news == null) return null;
                news.Enabled = enabled;
                await _memberRepository.UpdateAsync(news);
                await _unitOfWork.SaveChangesAsync();
                return Result.Successed("设置成功!");

            }
            catch (Exception ex)
            {
                _logger.LogError("设置会员管理是否可用异常", ex);
                throw;
            }
        }
        #endregion
    }
}
